<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Promise封装AJAX</title>
</head>
<body>
<h1>Promise封装AJAX</h1>
<hr>
<button>使用回调函数发送AJAX</button>


<script>
  //接口地址 https://api.apiopen.top/getJoke
  //获取元素对象
  const btn=document.querySelector('button')


  //旧方案
  btn.addEventListener('click',function (){
      const p=new Promise((resolve,reject)=>{
          //创建对象
          const xhr=new XMLHttpRequest()
          //初始化
          xhr.open('GET',' https://api.apiopen.top/getJoke')
          //发送
          xhr.send()
          //绑定事件，处理响应结果
          xhr.onreadystatechange=function () {
              if (xhr.readyState === 4){
                  if (xhr.status>=200&&xhr.status<300){
                        resolve(xhr.response)
                  }else{
                      reject(xhr.status)
                  }
              }
          }
      }    )

      p.then(
          (value)=>{
              console.log(value)
          },
          (reason)=>{
              console.log(reason)
          }
      )



  })
</script>
</body>
</html>